package User

import (
	"context"
	"fmt"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"

	"Yoj/api/User/Regist"

	"Yoj/internal/dao"
	"Yoj/internal/model/do"
	"github.com/gogf/gf/v2/os/glog"
)

// 验证用户注册信息
func JudgeRegisterInfo(ctx context.Context, req *Regist.UserRegistReq) (err error) {
	// 判断用户名是否已存在
	isExist, err := dao.YUser.Ctx(ctx).Where("username = ?", req.Username).Exist()
	if err != nil {
		glog.Error(ctx, err)
		return gerror.NewCode(gcode.CodeInternalError, "查询数据出错")
	}
	if isExist {
		return gerror.NewCode(gcode.CodeInvalidParameter, "用户名已存在")
	}

	// 判断邮箱是否已存在
	isExist, err = dao.YUser.Ctx(ctx).Where("email = ?", req.Email).Exist()
	if err != nil {
		glog.Error(ctx, err)
		return gerror.NewCode(gcode.CodeInternalError, "查询数据出错")
	}
	if isExist {
		glog.Error(ctx, err)
		return gerror.NewCode(gcode.CodeInvalidParameter, "邮箱已存在")
	}

	return nil
}

// 插入用户注册信息
func InsertRegisterInfo(ctx context.Context, req *Regist.UserRegistReq) (rid int64, err error) {
	id, err := dao.YUser.Ctx(ctx).Data(do.YUser{
		Username: req.Username,
		Email:    req.Email,
		Password: req.UserPwd,
	}).InsertAndGetId()
	if err != nil {
		glog.Error(ctx, err)
		return id, gerror.NewCode(gcode.CodeInternalError, "插入数据出错")
	}
	return id, nil
}

// 加入默认组
func InsertToDefaultTeam(ctx context.Context, user_id int64) (err error) {
	_, err = dao.TeamMembers.Ctx(ctx).Data(do.TeamMembers{TeamId: 100000, UserId: user_id, Role: "default"}).Insert()
	if err != nil {
		glog.Error(ctx, err)
		return gerror.NewCode(gcode.CodeInternalError, "用户组数据插入失败")
	}
	return nil
}

func (c *ControllerRegist) UserRegist(ctx context.Context, req *Regist.UserRegistReq) (res *Regist.UserRegistRes, err error) {
	// 验证用户注册信息;
	if err = JudgeRegisterInfo(ctx, req); err != nil {
		return nil, err
	}

	// 插入用户注册信息;
	user_id, err := InsertRegisterInfo(ctx, req)
	if err != nil {
		return nil, err
	}

	err = InsertToDefaultTeam(ctx, user_id)
	if err != nil {
		return nil, err
	}

	res = &Regist.UserRegistRes{
		Qid:  fmt.Sprint(user_id),
		Name: req.Username,
	}

	return res, nil
}
